﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace NetMove01
{
    public class NetClient : NetBase
    {
        public override void Start(ERole er)
        {
            Role = er;
            try
            {
                string IP_ADDRESS = "192.168.1.77";
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(IP_ADDRESS), 11000);
                Handle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Handle.Connect(ipEndPoint);
                Handle.Blocking = false;
            }
            catch (Exception)
            {
            }
        }

        public override void Send(SendData sd) 
        {
            byte[] bytes = new byte[8];
            if(Handle!=null)
            if (Handle.Connected)
            {
                Handle.Send(sd.ToBytes());
            }
        }

        public override void Receive(out SendData sd)
        {
            sd.x = 0;
            sd.y = 0;
            byte[] bytes = new byte[8];
            if (Handle != null)
            if (Handle.Connected)
                if (Handle.Poll(0, SelectMode.SelectRead))
                {
                    int bytesRec = Handle.Receive(bytes);
                    sd.x = BitConverter.ToInt32(bytes, 0);
                    sd.y = BitConverter.ToInt32(bytes, 4);
                }
        }
    }
}
